package com.csj.mvvm.ui.main;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityOptionsCompat;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.FragmentActivity;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.CustomTarget;
import com.csj.mvvm.R;
import com.csj.mvvm.utils.CustomDialog;
import com.csj.mvvm.utils.SDCardUtils;
import com.csj.mvvm.utils.ToastUtil;
import com.csj.mvvm.utils.ZXingUtils;
import com.github.chrisbanes.photoview.PhotoView;

import java.io.File;

@SuppressLint("NewApi")
public class ImageActivity extends FragmentActivity {

    private static final String IMG = "img";
    private static final String TRANSITION_NAME = "image";
    private static final String IS_IMAGE = "is_image";
    private PhotoView ivImage;
    private ImageView ivClose;
    private String path;
    private boolean isImage;
    private Bitmap mBitmap;

    @SuppressLint("NewApi")
    public static void start(Context context, View view, String path) {
        start(context, view, path, true);
    }

    public static void start(Context context, View view, String path, boolean isImage) {
        if (TextUtils.isEmpty(path)) {
            return;
        }
        Intent intent = new Intent(context, ImageActivity.class);
        intent.putExtra(IMG, path);
        intent.putExtra(IS_IMAGE, isImage);
        ActivityOptionsCompat options = ActivityOptionsCompat.
                makeSceneTransitionAnimation((FragmentActivity) context, view, TRANSITION_NAME);
        context.startActivity(intent, options.toBundle());
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        DataBindingUtil.setContentView(this,R.layout.activity_image);
        init();
    }

    /**
     * 初始化
     */
    private void init() {
        ivImage = findViewById(R.id.iv_image);
        ivClose = findViewById(R.id.iv_image_close);
        initData();
        initListener();
    }

    private void initData() {
        // 加载图片
        path = getIntent().getStringExtra(IMG);
        isImage = getIntent().getBooleanExtra(IS_IMAGE, true);
        LinearLayout loading = findViewById(R.id.loading);
        ImageView img = findViewById(R.id.img);
        Animation animation = AnimationUtils.loadAnimation(this, R.anim.loading_animation);
        img.startAnimation(animation);
        // 如果不是图片，生成二维码图片
        if (isImage) {
            loading.setVisibility(View.VISIBLE);
            Glide.with(ivImage.getContext())
                    .asBitmap()
                    .load(path)
                    .placeholder(R.drawable.drawable_default)
                    .error(R.drawable.drawable_default)
                    .into(new CustomTarget<Bitmap>() {
                        @Override
                        public void onResourceReady(@NonNull Bitmap resource, @Nullable com.bumptech.glide.request.transition.Transition<? super Bitmap> transition) {
                            mBitmap = resource;
                            // 设置图片
                            ivImage.setImageBitmap(mBitmap);
                            loading.setVisibility(View.GONE);
                        }

                        @Override
                        public void onLoadCleared(@Nullable Drawable placeholder) {
                            loading.setVisibility(View.GONE);
                        }
                    });
        } else {
            mBitmap = ZXingUtils.createQRImage(path, dip2px(this, 200), dip2px(this, 200));
            ivImage.setImageBitmap(mBitmap);
//            Glide.with(ivImage.getContext()).load(mBitmap)
//                    .placeholder(R.drawable.drawable_default)
//                    .error(R.drawable.drawable_default)
//                    .into(ivImage);
        }
    }


    /**
     * 事件监听
     */
    private void initListener() {
        ivClose.setOnClickListener(v -> {
            onBackPressed();
        });
        ivImage.setOnLongClickListener(v -> {
            if (mBitmap != null) {
                new CustomDialog.Builder(this).setView()
                        .setMessage("保存图片？")
                        .setPositiveButton((dialog, i) -> {
                            String fileName = "IMG_" + System.currentTimeMillis();
                            SDCardUtils.getDefault().saveToSdCard(mBitmap, fileName, new SDCardUtils.OnSaveCallback() {
                                @Override
                                public void success(File file) {
                                    ToastUtil.INSTANCE.showToast("保存成功");
                                }

                                @Override
                                public void failure() {
                                    ToastUtil.INSTANCE.showToast("保存失败");
                                }
                            });
                            dialog.dismiss();
                        }).show();
            }
            return true;
        });
    }


    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

}
